import {defineStore} from "pinia";
import {ElLoading} from "element-plus";

export const useCommonStore = defineStore("commonStore", {
    state: (): CommonStore => ({
            screenWidth: document.body.clientWidth,
            loadingInstances: {}
        }
    ),
    getters: {},
    actions: {
        /**
         * 改变屏幕宽度
         * @param {number} data 屏幕宽度
         */
        changeScreenWidth(data: number) {
            this.screenWidth = data;
        },
        /**
         * 根据参数打开指定加载动画
         * @param options
         * @param id
         */
        openLoading(options?: LoadingOptions, id: string = "default") {
            //关闭指定id对应的实例，防止对象不可回收
            this.closeLoading(id);
            if (options) {
                this.loadingInstances[id] = ElLoading.service(options);
            } else {
                this.loadingInstances[id] = ElLoading.service({
                    fullscreen: true,
                    lock: true
                });
            }
        },
        /**
         * 关闭指定加载动画
         * @param id
         */
        closeLoading(id: string = "default") {
            this.loadingInstances[id]?.close();
            this.loadingInstances[id] = null
        }
    },
});
